package com.qf.springboot.interceptor;

import com.qf.springboot.entity.User;
import com.qf.springboot.service.UserService;
import com.qf.springboot.utils.Constants;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@Component
public class LoginInterceptor implements HandlerInterceptor {
    @Autowired
    private UserService userService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute(Constants.SESSION_USER_KEY);
        if (user != null) {
            //user不为空表示已登录，跳转到首页
            response.sendRedirect("/plateform.html");
            return false;
        } else {
            //user为空表示还未登录，查看cookie中是否有记录，如果有则自动登录
            Cookie[] cookies = request.getCookies();
            String cookieName = null;
            String cookiePassword = null;
            if (cookies != null && cookies.length > 0) {
                for (Cookie cookie : cookies) {
                    if (cookie.getName().equals("username")) {
                        cookieName = cookie.getValue();
                    }
                    if (cookie.getName().equals("password")) {
                        cookiePassword = cookie.getValue();
                    }
                    User cookieUser = userService.checkCookieUsernameAndPassword(cookieName, cookiePassword);
                    if (cookieUser != null) {
                        session.setAttribute(Constants.SESSION_USER_KEY, cookieUser);
                        response.sendRedirect("/plateform.html");
                        return false;
                    }
                }
            }
            //cookie中没有免登录的用户，放行
            return true;
        }
    }
}
